<template>
  <div class="users-container">
    <div class="header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <div class="search-box">
          <input 
            v-model="searchKeyword" 
            @input="handleSearch"
            type="text" 
            placeholder="搜索用户ID或用户名..."
            class="search-input"
          />
          <i class="material-icons search-icon">search</i>
        </div>
        <button @click="showAddDialog = true" class="btn btn-primary">
          <i class="material-icons">person_add</i>
          添加用户
        </button>
      </div>
    </div>
    
    <div class="content">
      <!-- 统计信息 -->
      <div class="stats-bar">
        <div class="stat-item">
          <span class="stat-label">总用户数:</span>
          <span class="stat-value">{{ totalUsers }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">活跃用户:</span>
          <span class="stat-value">{{ activeUsers }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">禁用用户:</span>
          <span class="stat-value">{{ inactiveUsers }}</span>
        </div>
      </div>

      <!-- 用户表格 -->
      <div class="users-table">
        <div v-if="loading" class="loading">
          <i class="material-icons loading-icon">refresh</i>
          <span>加载中...</span>
        </div>
        
        <table v-else>
          <thead>
            <tr>
              <th>用户ID</th>
              <th>用户名</th>
              <th>性别</th>
              <th>等级</th>
              <th>积分</th>
              <th>经验值</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in filteredUsers" :key="user.userId">
              <td>{{ user.userId }}</td>
              <td>{{ user.userName || '未设置' }}</td>
              <td>{{ user.userSex === 1 ? '男' : user.userSex === 0 ? '女' : '未知' }}</td>
              <td>
                <span class="level-badge">Lv{{ user.level || 1 }}</span>
              </td>
              <td>{{ user.points || 0 }}</td>
              <td>{{ user.experiencePoints || 0 }}</td>
              <td>
                <span :class="['status', user.delTag === 1 ? 'active' : 'inactive']">
                  {{ user.delTag === 1 ? '正常' : '禁用' }}
                </span>
              </td>
              <td class="actions">
                <button @click="openEditDialog(user)" class="action-btn edit">
                  <i class="material-icons">edit</i>
                  编辑
                </button>
                <button @click="toggleUserStatus(user)" class="action-btn toggle">
                  <i class="material-icons">{{ user.delTag === 1 ? 'block' : 'check_circle' }}</i>
                  {{ user.delTag === 1 ? '禁用' : '启用' }}
                </button>
                <button @click="deleteUser(user)" class="action-btn delete">
                  <i class="material-icons">delete</i>
                  删除
                </button>
              </td>
            </tr>
            <tr v-if="filteredUsers.length === 0">
              <td colspan="10" class="no-data">暂无用户数据</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="totalPages > 1">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage <= 1"
          class="page-btn"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage >= totalPages"
          class="page-btn"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 添加用户对话框 -->
    <div v-if="showAddDialog" class="modal-overlay" @click="closeAddDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>添加新用户</h3>
          <button @click="closeAddDialog" class="close-btn">
            <i class="material-icons">close</i>
          </button>
        </div>
        <form @submit.prevent="addUser" class="user-form">
          <div class="form-group">
            <label>用户ID *</label>
            <input v-model="newUser.userId" type="text" required placeholder="请输入用户ID">
          </div>
          <div class="form-group">
            <label>用户名</label>
            <input v-model="newUser.userName" type="text" placeholder="请输入用户名">
          </div>
          <div class="form-group">
            <label>手机号</label>
            <input v-model="newUser.userPhone" type="tel" placeholder="请输入手机号">
          </div>
          <div class="form-group">
            <label>性别</label>
            <select v-model="newUser.userSex">
              <option value="1">男</option>
              <option value="0">女</option>
            </select>
          </div>
          <div class="form-group">
            <label>初始等级</label>
            <select v-model="newUser.level">
              <option value="1">Lv1 普通会员</option>
              <option value="2">Lv2 银牌会员</option>
              <option value="3">Lv3 金牌会员</option>
              <option value="4">Lv4 钻石会员</option>
              <option value="5">Lv5 至尊会员</option>
            </select>
          </div>
          <div class="form-group">
            <label>初始积分</label>
            <input v-model.number="newUser.points" type="number" min="0" placeholder="0">
          </div>
          <div class="form-actions">
            <button type="button" @click="closeAddDialog" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary" :disabled="addingUser">
              {{ addingUser ? '添加中...' : '添加用户' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑用户对话框 -->
    <div v-if="showEditDialog" class="modal-overlay" @click="closeEditDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>编辑用户信息</h3>
          <button @click="closeEditDialog" class="close-btn">
            <i class="material-icons">close</i>
          </button>
        </div>
        <form @submit.prevent="updateUser" class="user-form">
          <div class="form-group">
            <label>用户ID</label>
            <input v-model="editingUser.userId" type="text" readonly class="readonly">
          </div>
          <div class="form-group">
            <label>用户名</label>
            <input v-model="editingUser.userName" type="text" placeholder="请输入用户名">
          </div>
          <div class="form-group">
            <label>手机号</label>
            <input v-model="editingUser.userPhone" type="tel" placeholder="请输入手机号">
          </div>
          <div class="form-group">
            <label>性别</label>
            <select v-model="editingUser.userSex">
              <option value="1">男</option>
              <option value="0">女</option>
            </select>
          </div>
          <div class="form-group">
            <label>等级</label>
            <select v-model="editingUser.level">
              <option value="1">Lv1 普通会员</option>
              <option value="2">Lv2 银牌会员</option>
              <option value="3">Lv3 金牌会员</option>
              <option value="4">Lv4 钻石会员</option>
              <option value="5">Lv5 至尊会员</option>
            </select>
          </div>
          <div class="form-group">
            <label>积分</label>
            <input v-model.number="editingUser.points" type="number" min="0">
          </div>
          <div class="form-group">
            <label>经验值</label>
            <input v-model.number="editingUser.experiencePoints" type="number" min="0">
          </div>
          <div class="form-actions">
            <button type="button" @click="closeEditDialog" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary" :disabled="updatingUser">
              {{ updatingUser ? '更新中...' : '更新用户' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Users',
  data() {
    return {
      users: [],
      filteredUsers: [],
      loading: false,
      searchKeyword: '',
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      
      // 对话框状态
      showAddDialog: false,
      showEditDialog: false,
      addingUser: false,
      updatingUser: false,
      
      // 新用户表单
      newUser: {
        userId: '',
        userName: '',
        userPhone: '',
        userSex: 1,
        level: 1,
        points: 0,
        experiencePoints: 0
      },
      
      // 编辑用户表单
      editingUser: {}
    }
  },
  
  computed: {
    totalPages() {
      return Math.ceil(this.totalUsers / this.pageSize)
    },
    
    activeUsers() {
      return this.users.filter(user => user.delTag === 1).length
    },
    
    inactiveUsers() {
      return this.users.filter(user => user.delTag === 0).length
    }
  },
  
  mounted() {
    this.fetchUsersList()
  },
  
  methods: {
    async fetchUsersList() {
      this.loading = true
      try {
        // 将分页参数和搜索关键字传给后端接口
        const keyword = this.searchKeyword && this.searchKeyword.trim() ? this.searchKeyword.trim() : ''
        const response = await axios.post('http://localhost:8888/elm/admin/users/list', null, {
          params: {
            page: this.currentPage,
            size: 1000,
            keyword: keyword || undefined
          }
        })
        
        console.log('用户列表响应:', response.data)
        
        if (response.data.code === 200 || response.data.code === '200') {
          const result = response.data.result || {}
          this.users = result.users || []
          // total 使用后端返回的总数，更符合真实分页
          this.totalUsers = result.total || this.users.length
          this.applyFilters()
          console.log('获取到用户数量:', this.users.length)
        } else {
          console.error('API返回错误:', response.data)
          this.users = []
          this.filteredUsers = []
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.users = []
        this.filteredUsers = []
        alert('获取用户列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },
    
    applyFilters() {
      let filtered = [...this.users]
      
      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(user => 
          (user.userId && user.userId.toLowerCase().includes(keyword)) ||
          (user.userName && user.userName.toLowerCase().includes(keyword))
        )
      }
      
      // 分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.filteredUsers = filtered.slice(start, end)
      this.totalUsers = filtered.length
    },
    
    handleSearch() {
      this.currentPage = 1
      this.applyFilters()
    },
    
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
        this.applyFilters()
      }
    },
    
    // 显示编辑对话框
    openEditDialog(user) {
      this.editingUser = { ...user }
      this.showEditDialog = true
    },
    
    // 关闭对话框
    closeAddDialog() {
      this.showAddDialog = false
      this.resetNewUser()
    },
    
    closeEditDialog() {
      this.showEditDialog = false
      this.editingUser = {}
    },
    
    resetNewUser() {
      this.newUser = {
        userId: '',
        userName: '',
        userPhone: '',
        userSex: 1,
        level: 1,
        points: 0,
        experiencePoints: 0
      }
    },
    
    // 添加用户
    async addUser() {
      if (!this.newUser.userId.trim()) {
        alert('请输入用户ID')
        return
      }
      
      this.addingUser = true
      try {
        const userData = {
          userId: this.newUser.userId.trim(),
          userName: this.newUser.userName.trim() || this.newUser.userId,
          userPhone: this.newUser.userPhone.trim(),
          userSex: parseInt(this.newUser.userSex),
          level: parseInt(this.newUser.level),
          points: parseInt(this.newUser.points) || 0,
          experiencePoints: parseInt(this.newUser.experiencePoints) || 0,
          delTag: 1,
          password: '123456' // 默认密码
        }
        
        await axios.post('http://localhost:8888/elm/admin/users/add', userData)
        
        alert('用户添加成功')
        this.closeAddDialog()
        await this.fetchUsersList()
      } catch (error) {
        console.error('添加用户失败:', error)
        const message = error.response?.data?.message || error.message || '添加用户失败'
        alert('添加用户失败: ' + message)
      } finally {
        this.addingUser = false
      }
    },
    
    // 更新用户
    async updateUser() {
      this.updatingUser = true
      try {
        const userData = {
          ...this.editingUser,
          userSex: parseInt(this.editingUser.userSex),
          level: parseInt(this.editingUser.level),
          points: parseInt(this.editingUser.points) || 0,
          experiencePoints: parseInt(this.editingUser.experiencePoints) || 0
        }
        
        await axios.post('http://localhost:8888/elm/admin/users/update', userData)
        
        alert('用户信息更新成功')
        this.closeEditDialog()
        await this.fetchUsersList()
      } catch (error) {
        console.error('更新用户失败:', error)
        const message = error.response?.data?.message || error.message || '更新用户失败'
        alert('更新用户失败: ' + message)
      } finally {
        this.updatingUser = false
      }
    },
    
    // 切换用户状态
    async toggleUserStatus(user) {
      const action = user.delTag === 1 ? '禁用' : '启用'
      if (!confirm(`确定要${action}用户 ${user.userName || user.userId} 吗？`)) {
        return
      }
      
      try {
        const newStatus = user.delTag === 1 ? 0 : 1
        await axios.post('http://localhost:8888/elm/admin/users/status', null, {
          params: {
            userId: user.userId,
            status: newStatus
          }
        })
        
        user.delTag = newStatus
        alert(`用户${action}成功`)
        this.applyFilters() // 重新应用过滤器更新显示
      } catch (error) {
        console.error('更新用户状态失败:', error)
        alert('更新用户状态失败')
      }
    },
    
    // 删除用户
    async deleteUser(user) {
      if (!confirm(`确定要删除用户 ${user.userName || user.userId} 吗？此操作不可恢复！`)) {
        return
      }
      
      try {
        await axios.post('http://localhost:8888/elm/admin/users/delete', null, {
          params: { userId: user.userId }
        })
        
        alert('用户删除成功')
        await this.fetchUsersList()
      } catch (error) {
        console.error('删除用户失败:', error)
        const message = error.response?.data?.message || error.message || '删除用户失败'
        alert('删除用户失败: ' + message)
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未知'
      
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return '无效日期'
        
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        return '日期错误'
      }
    }
  }
}
</script>

<style scoped>
.users-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  padding: 20px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.btn-primary {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF5252 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.3);
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

.users-table {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background-color: #f5f5f5;
}

th {
  padding: 15px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #eee;
}

td {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.status {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.status.active {
  background-color: #d4edda;
  color: #155724;
}

.status.inactive {
  background-color: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn.edit {
  background-color: #e3f2fd;
  color: #1976d2;
}

.action-btn.edit:hover {
  background-color: #bbdefb;
}

.action-btn.toggle {
  background-color: #fff3e0;
  color: #f57c00;
}

.action-btn.toggle:hover {
  background-color: #ffe0b2;
}

.action-btn.delete {
  background-color: #ffebee;
  color: #c62828;
}

.action-btn.delete:hover {
  background-color: #ffcdd2;
}

/* 新增样式 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  padding: 10px 40px 10px 15px;
  border: 1px solid #ddd;
  border-radius: 25px;
  font-size: 14px;
  width: 300px;
  transition: all 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #FF6B6B;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
}

.search-icon {
  position: absolute;
  right: 15px;
  color: #999;
  font-size: 20px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.btn-secondary {
  background: #f8f9fa;
  color: #6c757d;
  border: 1px solid #dee2e6;
}

.btn-secondary:hover:not(:disabled) {
  background: #e9ecef;
}

.stats-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 20px;
  border-radius: 8px;
  background: #f8f9fa;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #666;
}

.loading-icon {
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.no-data {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 40px;
}

.level-badge {
  display: inline-block;
  padding: 4px 8px;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.action-btn .material-icons {
  font-size: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #FF6B6B;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.user-form {
  padding: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #FF6B6B;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
}

.form-group input.readonly {
  background-color: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
  }
  
  .search-input {
    width: 200px;
  }
  
  .stats-bar {
    flex-direction: column;
    gap: 10px;
  }
  
  .actions {
    flex-direction: column;
  }
  
  .action-btn {
    justify-content: center;
  }
  
  .modal-content {
    margin: 20px;
    width: calc(100% - 40px);
  }
  
  .user-form {
    padding: 20px;
  }
}
</style>
